package com.dh.service.impl;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.dh.core.common.enums.BizExceptionEnum;
import com.dh.core.common.exception.BussinessException;
import com.dh.dao.RoleDao;
import com.dh.dto.RoleDTO;
import com.dh.entity.Role;
import com.dh.service.RoleService;

/**
 * @author 作者 dinghao
 * @version 创建时间：2018年11月26日 下午2:23:29
 * @Description 类说明 :
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;

	@Override
	public Page<Role> findRoleList(String option, Integer page, Integer pagesize, String sort, String order) {
		Role role = new Role();
		Example<Role> example = Example.of(role);
		if (StringUtils.isNotBlank(option)) {
			role.setName(option);
		}
		PageRequest pageable = null;
		if (StringUtils.isNotBlank(sort)) {
			Direction direction = Direction.ASC.toString().equals(order) ? Direction.ASC : Direction.DESC;
			Sort Sort = new Sort(direction, sort);
			pageable = PageRequest.of(page, pagesize, Sort);
		} else {
			pageable = PageRequest.of(page, pagesize);
		}
		return roleDao.findAll(example, pageable);
	}

	@Override
	public Role addRole(RoleDTO roleDTO) {
		Role role = new Role(StringUtils.isNotBlank(roleDTO.getRid()) ? roleDTO.getRid() : UUID.randomUUID().toString(), roleDTO.getName());
		return roleDao.save(role);
	}

	@Override
	public Role updateRole(RoleDTO roleDTO) {
		try {
			Role role = roleDao.findById(roleDTO.getRid()).get();
			if (StringUtils.isNotBlank(roleDTO.getName())) {
				role.setName(roleDTO.getName());
			}
			return roleDao.save(role);
		} catch (Exception e) {
			throw new BussinessException(BizExceptionEnum.ROLE_NOT_PRESENT);
		}
	}

}
